<template>
  <div class="variable-stability">
    <a-row>
      <a-col :span="12">
        <span>指标</span>
        <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange"> 全部 </a-checkbox>
        <a-checkbox-group v-model="checkedList" :options="plainOptions" @change="onChange" />
      </a-col>
      <a-col :span="1" :offset="11">
        <a-icon
          type="bar-chart"
          :style="{ fontSize: '24px', cursor: 'pointer' }"
          :class="['chart-icon', chartType === 'bar' ? 'active' : '']"
          @click="handleChartTypeChange('bar')"
        />
        <a-icon
          type="line-chart"
          :style="{ fontSize: '24px', cursor: 'pointer' }"
          :class="['chart-icon', chartType === 'line' ? 'active' : '']"
          @click="handleChartTypeChange('line')"
        />
      </a-col>
    </a-row>
    <template v-if="dataSource.length">
      <a-row v-for="item in calcChartOption" :key="item.title">
        <div class="chart-wrapper">
          <echart :option="item.option" v-if="item.option" />
          <div v-else class="empty-state">
            <Empty :description="item.emptyText" />
          </div>
        </div>
      </a-row>
      <a-row v-if="isShowConfusionMatrix">
        <a-tabs :activeKey="activeKey" @tabChange="handleTabChange">
          <a-tab-pane v-for="(item, index) in summaryList" :key="item.tabTitle">
            <template #tab>
              <a-popover placement="bottomLeft">
                <template slot="content">
                  回流数据量{{ item.summary.backFlowSize }}，占比{{ item.summary.percent }}%。
                  <a-button :disabled="!item.summary.total" @click="showDetail(index)">搜索详情</a-button>
                </template>
                <div>{{ item.tabTitle }}</div>
              </a-popover>
            </template>
          </a-tab-pane>
        </a-tabs>
        <confusion-matrix :confusionMatrixData="confusionMatrix" />
      </a-row>
    </template>
    <a-modal
      title="评估列表详情"
      :visible="visible"
      width="1200px"
      @cancel="visible = false"
      @ok="visible = false"
    >
      <model-performance-detail :queryParam="queryParam" :dataSource="totalData" />
    </a-modal>
  </div>
</template>

<script>
import { Echart } from '@/components'
import { Empty } from 'ant-design-vue'
import { deepMerge, echartConfig } from './echart.config'
import ConfusionMatrix from '@/components/ConfusionMatrix'
import ModelPerformanceDetail from './ModelPerformanceDetail'

export default {
  name: 'ModelPerformance',
  components: {
    Echart,
    Empty,
    ConfusionMatrix,
    ModelPerformanceDetail,
  },
  props: {
    alertConfigField: {
      type: Array,
      default: () => [],
    },
    queryParam: {
      type: Object,
      default: () => ({}),
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    dataSource: {
      handler(newVal) {
        this.initChart(newVal)
      },
      deep: true,
      immediate: true,
    },
    checkedList: {
      handler(newVal) {
        console.log('checkedList', newVal)
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    calcChartOption() {
      return this.chartOption.filter((item) => this.checkedList.includes(item.title))
    },
    isShowConfusionMatrix() {
      return this.checkedList.includes('confusionMatrix')
    },
    summaryList() {
      return this.timeList.map((item, index) => ({
        tabTitle: item,
        summary: this.summary.find((_, i) => i === index),
      }))
    },
  },
  data() {
    return {
      chartOption: [],
      loading: false,
      plainOptions: [
        {
          label: 'AUC',
          value: 'AUC',
        },
        {
          label: 'KS',
          value: 'KS',
        },
        {
          label: '混淆矩阵',
          value: 'confusionMatrix',
        },
      ],
      indeterminate: false,
      checkAll: true,
      checkedList: ['AUC', 'KS', 'confusionMatrix'],
      confusionMatrix: [],
      chartType: 'line',
      timeList: [],
      summary: [],
      activeKey: '',
      visible: false,
      totalData: {},
    }
  },
  mounted() {
    // 注册全局事件处理函数
    window.handleTooltipDetailClick = this.handleTooltipDetailClick
    window.handleTooltipExportClick = this.handleTooltipExportClick
  },
  beforeDestroy() {
    // 清理全局事件处理函数
    delete window.handleTooltipDetailClick
    delete window.handleTooltipExportClick
  },
  methods: {
    initChart(val) {
      console.log('initChart', val)
      if (val.length === 0) {
        return
      }
      const [first] = val
      const { label, auc, ks, confusionMatrix, summary } = first
      this.confusionMatrix = confusionMatrix
      this.timeList = label
      this.summary = summary
      const renderOption = (option) => {
        if (!option.data) {
          return null
        }
        const { title, data, legend } = option
        const series = {
          data: data,
          type: 'line',
          name: title,
          smooth: true,
        }
        const _this = this
        return deepMerge(echartConfig, {
          title: {
            text: title,
          },
          tooltip: {
            trigger: 'axis',
            // 关键配置：让 tooltip 支持鼠标交互
            enterable: true,
            triggerOn: 'mousemove|click',
            position: (point) => {
              return [point[0], point[1]]
            },
            hideDelay: 300,
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#ccc',
            borderWidth: 1,
            textStyle: {
              color: '#333',
            },
            extraCssText: 'box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); border-radius: 4px;',
            formatter: function (params) {
              let result = '<div style="padding: 8px;">'
              result += '<div style="font-weight: bold; margin-bottom: 8px;">日期: ' + params[0].name + '</div>'

              params.forEach((param, index) => {
                result += '<div style="margin-bottom: 4px;">'
                result += param.marker + ' ' + param.seriesName + ': <strong>' + param.value + '</strong>'
                result += '</div>'
                result += '<div style="color: #666; font-size: 12px; margin-bottom: 8px;">'
                result += `回流数据量${_this.summary[index].backFlowSize}，占比${_this.summary[index].percent}%`
                result += '</div>'
              })

              // 添加按钮区域
              result +=
                '<div style="margin-top: 12px; padding-top: 8px; border-top: 1px solid #eee; text-align: center;">'
              result += '<button '
              result += 'id="tooltip-detail-btn-' + params[0].dataIndex + '" '
              result += 'style="'
              result += 'background: #1890ff; '
              result += 'color: white; '
              result += 'border: none; '
              result += 'padding: 6px 16px; '
              result += 'border-radius: 4px; '
              result += 'cursor: pointer; '
              result += 'margin-right: 8px; '
              result += 'font-size: 12px; '
              result += 'transition: all 0.3s;" '
              result += 'onmouseover="this.style.background=\'#40a9ff\'" '
              result += 'onmouseout="this.style.background=\'#1890ff\'" '
              result +=
                'onclick="window.handleTooltipDetailClick(\'' + params[0].name + "', " + params[0].dataIndex + ')">'
              result += '搜索详情'
              result += '</button>'

              result += '</div>'
              result += '</div>'

              return result
            },
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985',
              },
            },
          },
          xAxis: {
            data: label,
          },
          legend: {
            data: [legend],
          },
          series,
        })
      }
      this.chartOption = [
        {
          title: 'AUC',
          data: auc,
          emptyText: '暂无AUC数据',
          legend: '实际业务发生时间(表现期10天)',
        },
        {
          title: 'KS',
          data: ks,
          emptyText: '暂无KS数据',
          legend: '实际业务发生时间(表现期10天)',
        },
      ].map((item) => {
        return {
          title: item.title,
          option: renderOption(item),
          emptyText: item.emptyText,
        }
      })
    },
    onChange(checkedList) {
      this.indeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length
      this.checkAll = checkedList.length === this.plainOptions.length
    },
    onCheckAllChange(e) {
      Object.assign(this, {
        checkedList: e.target.checked ? this.plainOptions.map((item) => item.value) : [],
        indeterminate: false,
        checkAll: e.target.checked,
      })
    },
    handleChartTypeChange(type) {
      this.chartType = type
      this.chartOption = this.chartOption.map((item) => {
        return {
          ...item,
          option: {
            ...item.option,
            series: {
              ...item.option.series,
              type,
            },
          },
        }
      })
    },
    handleTabChange(key) {
      this.activeKey = key
    },
    showDetail(index) {
      this.visible = true
      this.totalData = this.summary.find((_, i) => i === index)
    },

    // 添加处理 tooltip 按钮点击的方法
    handleTooltipDetailClick(date, dataIndex) {
      console.log('查看详情点击', { date, dataIndex })
      // 在这里添加查看详情的逻辑
      this.showDetail(dataIndex)
    },
  },
}
</script>

<style lang="less" scoped>
.variable-stability {
  .chart-wrapper {
    margin-top: 12px;
    padding: 36px;
    .empty-state {
      padding: 40px 0;
      text-align: center;
      background-color: rgb(251, 251, 251);
      border-radius: 4px;
      border: 1px solid rgb(238, 238, 238);
    }
  }
  .chart-icon {
    &.active {
      // 当前主题色
      color: @primary-color;
    }
  }
}
</style>
